package com.tuanzi.loan.business.service.statistics.impl;

import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.HttpResult;
import com.base.common.http.model.PostData;
import com.base.common.http.model.RequestHeader;
import com.tuanzi.loan.business.entity.shortlink.ShortLink;
import com.tuanzi.loan.business.repository.statistics.custom.SmsStatisticsRepository;
import com.tuanzi.loan.business.service.shortlink.ShortLinkService;
import com.tuanzi.loan.business.service.statistics.SmsStatisticsService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.statistics.RecordRequest;
import com.tuanzi.loan.vo.request.statistics.SmsStatisticsRequest;
import com.tuanzi.loan.vo.response.statistics.SmsStatisticsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Date;

@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
@Slf4j
public class SmsStatisticsServiceImpl implements SmsStatisticsService {

	@Autowired
	private SmsStatisticsRepository smsStatisticsRepository;

	@Autowired
	private ShortLinkService shortLinkService;

	@Value("${xhh.host}")
	private String xhhHost;

	@Value("${remote.api.arr}")
	private String api;

	@Override
	public Page<SmsStatisticsResponse> list(PageSearcher<SmsStatisticsRequest> pageSearcher) {
		Page<SmsStatisticsResponse> list = smsStatisticsRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
		for (SmsStatisticsResponse response : list) {
			if (StringUtils.isNotEmpty(response.getShortLink())) {
				ShortLink shortLink = shortLinkService.findByShortLink(response.getShortLink());
				if (shortLink != null) {
					MultiValueMap<String, String> queryParams = null;
					try {
						UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(shortLink.getUrl()).build();
						queryParams = uriComponents.getQueryParams();
						String channel = queryParams.getFirst("channel");
						String activity = queryParams.getFirst("activity");

						SmsStatisticsResponse.ActivityRegisterRecord record;
						if (xhhHost.equals(uriComponents.getHost())) {
							try {
								RequestHeader requestHeader = new RequestHeader();
								requestHeader.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
								PostData postData = new PostData(GsonUtils.toJson(RecordRequest.builder().channel(channel).activity(activity).date(response.getExecuteTime().getTime()).build()));
								HttpResult httpResult = HttpClientUtil.post(requestHeader, api, postData);
								String responseBody = httpResult.getStringData();
								record = GsonUtils.toObject(responseBody, SmsStatisticsResponse.ActivityRegisterRecord.class);
							} catch (Exception e) {
								log.error("获取熊花花活动注册记录时发生网络异常", e);
								record = new SmsStatisticsResponse.ActivityRegisterRecord();
							}
						} else {
							record = getRecord(channel, activity, response.getExecuteTime());
						}
						BeanUtils.copyProperties(record, response);
					} catch (Exception e) {
						log.warn("短链[{}]对应的url[{}]无效", response.getShortLink(), shortLink.getUrl());
					}
				}
			}
		}
		return list;
	}

	@Override
	public SmsStatisticsResponse.ActivityRegisterRecord getRecord(String channel, String activity, Date date) {
		return smsStatisticsRepository.getRecord(channel, activity, date);
	}
}
